import { QuerySortArr } from '@dataui/crud-request';
import { objKeys } from '@dataui/crud-util';
import { FindOptionsOrder, FindOptionsOrderValue } from 'typeorm';
import { isFindOptionsOrder } from '../utils/type.utils';

export function deepSetSort(order: FindOptionsOrder<any>, parents: string[] = []): QuerySortArr[] | undefined {
  if (!order) return undefined;
  let sort: QuerySortArr[] = [];
  objKeys(order).forEach((field) => {
    const item = order[field];
    const fieldChain = parents.concat(field);
    if (isFindOptionsOrder(item)) {
      sort = sort.concat(deepSetSort(item, fieldChain));
    } else if (typeof item !== 'object') {
      const desc: FindOptionsOrderValue[] = ['DESC', 'desc', 1];
      sort.push([fieldChain.join('.'), desc.includes(item) ? 'DESC' : 'ASC']);
    } else {
      sort.push([fieldChain.join('.'), item.direction.toUpperCase() as 'DESC' | 'ASC']);
    }
  });
  return sort;
}
